package 语法.解析数据


def file = new File('../../../groovy_test.iml');
//遍历文件内容
file.eachLine {
    line -> println line
}
println '----------------------------------------'

//获取文件的内容
def text = file.getText()
println text
println '----------------------------------------'

//返回是一个列表，每一行内容都存在集合中
def result = file.readLines()
println result
println '----------------------------------------'

//得到当前文件的闭包
def reader = file.withReader {
    reader ->
        //只读取一百个字符
        char[] buffer = new char[100]
        reader.read(buffer)
        return buffer
}
println reader
println '----------------------------------------'


//实现一个拷贝
//不用我们关闭流，groovy自动帮我们关闭你了
def copy(String SourcePath, String destPath) {
    //创建目标文件
    def destFile = new File(destPath);
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    new File(SourcePath).withReader {
        read ->
            //拿到源文件所有内容
            def lines = read.readLines()
            //将文件内容拷贝
            destFile.withWriter {
                    //逐行拷贝
                write ->
                    lines.each {
                        line ->
                            write.append(line + "\r\n")
                    }
            }

    }
}

copy("../../../groovy_test.iml", "1.txt")
println '----------------------------------------'

//对象从内存存入文件
//将对象object写入path下的文件
def saveObject(Object object,String path){
    def destFile = new File(path);
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    //往目标文件写对象
    destFile.withObjectOutputStream {
        out ->
            out.writeObject(object)
    }
}
//对象从文件读入内存
def readObject(String path){
    def obj = null;
    def destFile = new File(path);
    destFile.withObjectInputStream {
        input ->
            def object = input.readObject()
            return object
    }
}
println '----------------------------------------'

